<template>
    <div class=" h-10 pl-2 pr-2 bg-[var(--active)] flex justify-between items-center rounded-full hover:scale-105 transition-transform duration-300 cursor-pointer"
        @click="playVoice">

        <!-- 麦克风图标 -->
        <div
            class="flex items-center">
            <el-icon :size="20" class="text-[var(--icon)]">
                <Mic />
            </el-icon>
        </div>
        <div class="flex mr-3">
            <!-- 语言签名信息 -->
            <div class="flex flex-col text-[var(--text)]">
                <span class="text-xs">{{ formatVoiceLength(voiceSign.voiceLength) }}</span>
            </div>
            <!-- 音波动画 -->
            <div v-if="isPlaying" class="flex items-center ml-2 gap-0.5">
                <span v-for="i in 5" :key="i" class="w-0.5 h-4 bg-gradient-to-t rounded animate-bounce"
                    :class="`from-[var(--playBg)] to-[var(--active)]`" :style="`animation-delay: ${i * 0.1}s`" />
            </div>
        </div>

    </div>
</template>

<script setup lang="ts">
    import { ref, watch } from "vue";
    import { Mic } from '@element-plus/icons-vue'

    // Props 接收 voiceSign 数据
    interface VoiceSign {
        id: string;
        voiceLength: number; // 语音时长（秒）
        voiceUrl: string; // 语音地址
    }

    const props = defineProps < {
        voiceSign: VoiceSign;
    } > ();

    // 音频播放状态和对象
    const isPlaying = ref(false);
    const audio = ref < HTMLAudioElement | null > (null);

    // 播放语音
    const playVoice = () => {
        if (isPlaying.value) {
            audio.value?.pause();
            isPlaying.value = false;
        } else {
            audio.value = new Audio(props.voiceSign.voiceUrl);
            audio.value.play();
            isPlaying.value = true;

            // 监听播放结束
            audio.value.addEventListener("ended", () => {
                isPlaying.value = false;
            });
        }
    };

    // 格式化语音时长
    const formatVoiceLength = (length: number): string => {
        const minutes = Math.floor(length / 60);
        const seconds = length % 60;
        return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
    };

    // 监听状态变化并清理音频
    watch(isPlaying, (newVal) => {
        if (!newVal && audio.value) {
            audio.value.pause();
            audio.value.currentTime = 0;
        }
    });
</script>

<style scoped>
    /* 音波动画（更大幅度） */
    @keyframes bounce {

        0%,
        100% {
            transform: scaleY(0.3);
            opacity: 0.7;
        }

        50% {
            transform: scaleY(1);
            opacity: 1;
        }
    }
</style>